package com.mingtu.guards.activity;

import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseActivity;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.common.view.ContainsEmojiEditText;
import com.mingtu.guards.R;
import com.mingtu.guards.bean.ApproveTypeBean;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.uploadevent.view.ReportPictureVideo2;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ApproveApplyActivity extends BaseActivity {

    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.layout_type)
    LinearLayout layoutType;
    @BindView(R.id.edit_describe)
    ContainsEmojiEditText editDescribe;
    @BindView(R.id.tv_total_text_count)
    TextView tvTotalTextCount;
    @BindView(R.id.report_picture_video)
    ReportPictureVideo2 reportPictureVideo;
    @BindView(R.id.submit)
    Button submit;
    private OptionsPickerView pvOptions;
    private List<String> typeList = new ArrayList<>();
    private int[] positionArray = {0};
    private int textNum = 0;
    private List<ApproveTypeBean.ListBean> listBeans;
    private int auditId;
    private String auditName;
    private List<String> mylist = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_approve_apply;
    }

    @Override
    protected void initView() {
        setModuleTitle("审批申请");
    }

    @Override
    protected void initData() {
        editDescribe.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                textNum -= count;
                tvTotalTextCount.setText(textNum + "");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                textNum += count;
                tvTotalTextCount.setText(textNum + "");
            }

            @Override
            public void afterTextChanged(Editable s) {
                MyLogUtil.e("MyTest", "afterTextChanged==" + s.toString());
                String str = MyUtills.getEditText(editDescribe);
                editDescribe.setSelection(str.length());
            }
        });

        int screenWidth = ScreenUtils.getScreenWidth();
        int itemWidth = (screenWidth - SizeUtils.dp2px(5) * 2 - SizeUtils.dp2px(15) * 4) / 3;
        reportPictureVideo.setItemWidth(itemWidth);

    }

    @Override
    protected void getData() {
        approveType();
    }


    @OnClick({R.id.layout_type, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_type:
                if (typeList.size() == 0) {
                    ToastUtils.showLong("暂无审核类型哦~");
                    return;
                }
                initOptionPicker();
                break;
            case R.id.submit:
                if (StringUtils.isEmpty(UIUtils.getTextView(tvType))) {
                    ToastUtils.showLong("请选择审批类型~");
                    return;
                }

                if (StringUtils.isEmpty(UIUtils.getEditText(editDescribe))) {
                    ToastUtils.showLong("请填写申请内容~");
                    return;
                }

                List<LinkedHashMap<String, Object>> picVideoUrl = reportPictureVideo.getPicVideoUrl();
                if (picVideoUrl.size() == 0) {
                    ToastUtils.showLong("请上传图片或者视频！");
                    return;
                }
                //每次请求的时候需要重新获取url
                mylist = new ArrayList<>();
                for (int i = 0; i < picVideoUrl.size(); i++) {
                    LinkedHashMap<String, Object> hashMap = picVideoUrl.get(i);
                    String url = (String) hashMap.get("url");
                    mylist.add(url);
                }
                approveSumit();
                break;
        }
    }

    /**
     * 审批类型
     */
    private void approveType() {
        OkGo.<String>post(MyConstant.POST_APPROVE_TYPE)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                ApproveTypeBean approveTypeBean = new ApproveTypeBean();
                                approveTypeBean = gson.fromJson(result, ApproveTypeBean.class);

                                if (approveTypeBean != null) {
                                    listBeans = approveTypeBean.getList();

                                    try {
                                        if (listBeans.size() > 0) {
                                            for (int i = 0; i < listBeans.size(); i++) {
                                                ApproveTypeBean.ListBean listBean = listBeans.get(i);
                                                String type = listBean.getName();
                                                typeList.add(type);
                                            }
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }


                        }
                    }
                });
    }

    /**
     * 条件选择器
     */

    private void initOptionPicker() {//条件选择器初始化

        pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                auditName = typeList.get(options1);
                tvType.setText(auditName);
                tvType.setTextColor(getResources().getColor(R.color.text_color333));
                positionArray[0] = options1;
                auditId = listBeans.get(options1).getAuditId();

            }
        })

                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(getResources().getColor(R.color.black_eee))
                .setCancelColor(getResources().getColor(R.color.text_cancel_color))
                .setSubmitColor(getResources().getColor(R.color.text_submit_color))
                .setTextColorCenter(getResources().getColor(R.color.colorPrimary))
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .setOutSideColor(getResources().getColor(R.color.translucence)) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {

                    }
                })
                .build();

        pvOptions.setSelectOptions(positionArray[0]);
        pvOptions.setPicker(typeList);//进入页面就获取，默认不显示
        pvOptions.show();

    }

    /**
     * 审批申请
     */
    private void approveSumit() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("auditId", auditId);
        hashMap.put("auditName", auditName);
        hashMap.put("memo", UIUtils.getEditText(editDescribe));
        hashMap.put("urlList", mylist);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_APPROVE_APPLY)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("申请成功！");
                                ActivityUtil.removeActivity(ActivityUtil.getTopActivity());
                                EventBus.getDefault().post(new MyEventBus(MyConstant.REFRESH_APPROVE_DATA));
                            }
                        }
                    }
                });
    }
}